package com.base.doublepoint;

public class TwoSum {
    /**
     * 方法一与方法二都是基于双指针的思想，都是在固定一个值的情况下找另一个值的。方法一更优。
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        //双指针
        int left = 0, right = nums.length-1;
        while (left<right){
            int tmp = nums[left]+nums[right];
            if (tmp == target){
                return new int[]{left,right};
            }else if (tmp>target){
                right--;
            }else if (tmp<target){
                left++;
            }
        }
       return new int[2];

    }

    public int[] twoSum1(int[] numbers, int target) {
        /**
         * 固定的是从左到右的指针。
         */
        for (int i = 0; i < numbers.length; ++i) {
            int low = i + 1, high = numbers.length - 1;
            while (low <= high) {
                int mid = (high - low) / 2 + low;
                if (numbers[mid] == target - numbers[i]) {
                    return new int[]{i + 1, mid + 1};
                } else if (numbers[mid] > target - numbers[i]) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            }
        }
        return new int[]{-1, -1};
    }



    public static void main(String[] args) {
        TwoSum twoSum = new TwoSum();
        int[] nums = {1,2,3,4};
        int target = 7;
        twoSum.twoSum(nums,target);
    }
}
